package com.pederszt.foodiary.server;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;

import com.pederszt.foodiary.action.BaseAction;

public class FoodiaryServlet extends HttpServlet
{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		String uri = req.getRequestURI();
		uri = uri.substring(16);

		String service = uri.substring(0, uri.indexOf("/"));
		String action = uri.substring(uri.indexOf("/") + 1);

		try
		{
			Class serviceObj = Class.forName("com.pederszt.foodiary.action." + service.substring(0, 1).toUpperCase() + service.substring(1)
					+ "Action");

			Method m = serviceObj.getMethod(action);

			BaseAction s = (BaseAction) serviceObj.newInstance();

			for (Map.Entry<String, String[]> entry : ((Map<String, String[]>) req.getParameterMap()).entrySet())
			{
				String name = entry.getKey();
				String[] value = entry.getValue();
				if (value.length == 0)
				{
					continue;
				}

				try
				{
					Field f = serviceObj.getDeclaredField(name);
					f.setAccessible(true);

					if (f.getType().equals(String.class))
					{
						f.set(s, value[0]);
					}
					else if (f.getType().equals(Integer.class))
					{
						f.set(s, Integer.parseInt(value[0]));
					}
					else if (f.getType().equals(Double.class))
					{
						f.set(s, Double.parseDouble(value[0]));
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			JSON result = (JSON) m.invoke(s);

			result.write(resp.getWriter());
		}
		catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InstantiationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (NoSuchMethodException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (SecurityException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IllegalArgumentException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InvocationTargetException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println(service + " " + action);

	}

}
